package com.chatClient.ferradm.cs.newpaltz.edu;

import android.app.Activity;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import common.IMessageCollector;
import common.TextMessage;

import dcf.Component;
import dcf.Endpoint;
import dcf.InitializationException;

public class ChatClientWindow extends Activity implements IMessageCollector {

	/** Initialize the window component */
	Button cancelBtn;
	Button sendBtn;
	EditText chatEditText;
	TextView chatMessageWindow;
	ChatClientBehavior clientBehavior;
	TextView usernameTextView;
	String lsHost;
	int lsPort;
	String clientHost;
	int clientPort;
	String username;
	Endpoint lsEndpoint;
	Endpoint clientEndpoint;
	SharedPreferences pref;
	NetworkInfo networkInfo;
	String networkType;
	ConnectivityManager connectivityManager;
	SharedPreferences defaultManager;
	State networkState;

	public void chatBehavior(ChatClientBehavior clientBehavior) {
		this.clientBehavior = clientBehavior;

	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.clientgui);

		usernameTextView = (TextView) findViewById(R.id.username);
		cancelBtn = (Button) findViewById(R.id.cancel);
		sendBtn = (Button) findViewById(R.id.send);
		chatEditText = (EditText) findViewById(R.id.chatEditText);
		chatMessageWindow = (TextView) findViewById(R.id.chatMessageWindow);
		chatMessageWindow.append("\tWelcome to the chat !\n");

		defaultManager = PreferenceManager.getDefaultSharedPreferences(this);
		lsHost = defaultManager.getString("lsHost", "default");
		lsPort = Integer.decode(new String(defaultManager.getString("lsPort",
				"default")));
		clientHost = defaultManager.getString("clientHost", "default");
		clientPort = Integer.decode(new String(defaultManager.getString(
				"clientPort", "default")));
		username = defaultManager.getString("username", "default");
		usernameTextView.setText(username);
		sendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (clientBehavior.isReady()) {

					try {
						TextMessage txt = new TextMessage(username,
								chatEditText.getText().toString());
						clientBehavior.sendMessage(txt);
						Toast.makeText(ChatClientWindow.this, "Message sent",
								Toast.LENGTH_SHORT).show();
					} catch (Exception e) {
						Toast.makeText(
								ChatClientWindow.this,
								"Unable to send the message\nError: "
										+ e.toString(), Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
					}
					chatEditText.setText("");

				} else {
					System.out.println("ClientBehavior is not ready");
				}
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				chatEditText.setText("");
			}
		});

		Log.i("ONCREATE", "ONSTART OK");
		connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		Log.i("ONCREATE", "connectivityManager OK");
		networkInfo = connectivityManager.getActiveNetworkInfo();
		Log.i("ONCREATE", "networkInfo OK");
		if (networkInfo != null) {
			networkType = networkInfo.getTypeName();
			Log.i("ONCREATE", "networkType OK");
			networkState = networkInfo.getState();
			Log.i("ONCREATE", "getState OK");
			Log.i("ONCREATE", "Network info : "
					+ networkInfo.getDetailedState().toString() + " "
					+ networkInfo.getSubtypeName().toString());
			if (networkState.compareTo(State.CONNECTED) == 0) {
				/** Framework stuff */
				try {
					lsEndpoint = new Endpoint(lsHost, lsPort);
					clientEndpoint = new Endpoint(clientHost, clientPort);
					clientBehavior = new ChatClientBehavior(lsEndpoint,
							clientEndpoint);
					this.chatBehavior(clientBehavior);
					clientBehavior.setMessageCollector(this);
					clientBehavior.setUserName(username);
					Component clientComponent = new Component(clientEndpoint,
							clientBehavior);
				} catch (InitializationException e) {
					e.printStackTrace();
				}
			}

	}
	}

	@Override
	protected void onStart() {
		super.onStart();
		networkInfo = connectivityManager.getActiveNetworkInfo();
		Log.i("ONSTART", "networkInfo OK");
		if (networkInfo != null) {
			networkState = networkInfo.getState();
			Log.i("ONSTART", "getState OK");
			Log.i("ONSTART", "Network info : "
					+ networkInfo.getDetailedState().toString() + " "
					+ networkInfo.getSubtypeName().toString());
			if (networkState.compareTo(State.CONNECTED) != 0) {
				Toast.makeText(ChatClientWindow.this, "You've been disconnected !",Toast.LENGTH_LONG).show();
				chatMessageWindow.append("*********** Not Connected ! ***********");
				cancelBtn.setEnabled(false);
				sendBtn.setEnabled(false);
				chatEditText.setEnabled(false);
				chatEditText.setFocusable(false);

			}
		} else {
			Toast.makeText(ChatClientWindow.this, "You've been disconnected !",Toast.LENGTH_LONG).show();
			chatMessageWindow.append("*********** Not Connected ! ***********");
			cancelBtn.setEnabled(false);
			sendBtn.setEnabled(false);
			chatEditText.setEnabled(false);
			chatEditText.setFocusable(false);
		}

	}

	@Override
	public void addMessage(TextMessage message) {

		System.out.println("ClientWindow:addMessage():");
		System.out
				.println("   Adding message : " + message.getMessageContent());
		System.out.println(message.getSenderId() + ": "
				+ message.getMessageContent());
		final TextMessage msg = new TextMessage(message.getSenderId(), message
				.getMessageContent());

		addTextView(msg);
	}

	private void addTextView(final TextMessage message) {

		Thread backGroundThread = new Thread(new Runnable() {
			public void run() {
				try {

					Thread.sleep(1000);

					Message msg = new Message();
					Bundle b = new Bundle();
					b.putString("getMessageContent", message
							.getMessageContent().toString());
					b
							.putString("getSenderId", message.getSenderId()
									.toString());
					msg.setData(b);
					handle.sendMessage(msg);

				} catch (Throwable t) {
				}
			}
		});
		backGroundThread.start();
	}

	final Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			ChatClientWindow.this.chatMessageWindow.append(msg.getData()
					.getString("getSenderId")
					+ ": "
					+ msg.getData().getString("getMessageContent")
					+ "\n");
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (clientBehavior != null) {
			clientBehavior.shutDown();
		}
	}

}